<?php

class Academico_MaquinaalumnoController extends Zend_Controller_Action {

    const CAPACITY_TYPE_MEMORY = 0;
    const CAPACITY_TYPE_CPU = 1;
    const CAPACITY_TYPE_STORAGE = 2;
    const CAPACITY_TYPE_STORAGE_ALLOCATED = 3;
    const CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = 4;
    const CAPACITY_TYPE_PRIVATE_IP = 5;
    const CAPACITY_TYPE_SECONDARY_STORAGE = 6;
    const CAPACITY_TYPE_VLAN = 7;
    const CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8;
    const CAPACITY_TYPE_LOCAL_STORAGE = 9;

    public function init() {
        
    }

    /**
     * 
     */
    public function preDispatch() {
        // Autenticacion del usuario
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_helper->layout->disableLayout();
            $this->_forward("index", "index", "");
        } else {
            $identity = $auth->getIdentity();
            if ($identity['tipo_usuario'] == VirtualLabs_Admin_Usuario::ROL_ADMIN) {
                $this->_helper->layout->disableLayout();
                $this->_redirect('/');
            }
        }
        //fin de la autenicacion del usuario
    }

    /**
     * 
     */
    public function encendervmAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $vm = new VirtualLabs_Admin_Machine();
        try {
            if ($this->permiteEncender($this->getRequest()->getParam('codigo_vm'))) {
                $encenderResponse = $vm->encenderVM($this->getRequest()->getParam('codigo_vm'));
                if ($encenderResponse["startvirtualmachineresponse"]["jobid"]) {
                    echo Zend_Json_Encoder::encode(array('response' => array('jobid' => $encenderResponse["startvirtualmachineresponse"]["jobid"])));
                } else {
                    echo Zend_Json_Encoder::encode(array('response' => 'error'));
                }
            } else {
                echo Zend_Json_Encoder::encode(array('response' => 'error', 'message' => 'No es posible encender la maquina. Verifique el horario de encendido'));
            }
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getTraceAsString());
            echo Zend_Json_Encoder::encode(array('response' => 'error', 'message' => $exc->getMessage()));
        }
    }

    /**
     * 
     */
    public function apagarvmAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        try {
            $vm = new VirtualLabs_Admin_Machine();
            $apagarResponse = $vm->apagarVM($this->getRequest()->getParam('codigo_vm'));
            if ($apagarResponse["stopvirtualmachineresponse"]["jobid"]) {
                echo Zend_Json_Encoder::encode(array('response' => array('jobid' => $apagarResponse["stopvirtualmachineresponse"]["jobid"])));
            } else {
                echo Zend_Json_Encoder::encode(array('response' => 'error'));
            }
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getTraceAsString());
            echo Zend_Json_Encoder::encode(array('response' => 'error', 'message' => $exc->getMessage()));
        }
    }

    /**
     * 
     */
    public function vmAction() {
        //$debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
        $vmDao = new VirtualLabs_Admin_Machine();
        //$vm = $vmDao->getVirtualMachine(array('codigo_vm', 'codigo_perfil_encendido', 'codigo_laboratorio'), array('codigo_maquina_virtual' => array('criteria' => '=', 'value' => $this->getRequest()->getParam('codigo_maquina_virtual'))));
        $vm = $vmDao->getVirtualMachine(array('codigo_vm', 'codigo_laboratorio'), array('codigo_maquina_virtual' => array('criteria' => '=', 'value' => $this->getRequest()->getParam('codigo_maquina_virtual'))));

        $perfilEncedidoDao = new VirtualLabs_Admin_PerfilEncendido();
        $labDao = new VirtualLabs_Admin_Laboratorio();
        $laboratorio = $labDao->getLaboratorio('*', array('codigo_laboratorio' => array('criteria' => '=', 'value' => $vm['codigo_laboratorio'])));
        //$debugLog->debug("Laboratorio" .print_r($laboratorio,TRUE));
        //$perfilEncendido = $perfilEncedidoDao->getPerfilEncendido('*', array('codigo_perfil_encendido' => array('criteria' => '=', 'value' => $vm['codigo_perfil_encendido'])));
        $perfilEncendido = $perfilEncedidoDao->getPerfilEncendido('*', array('codigo_perfil_encendido' => array('criteria' => '=', 'value' => $laboratorio['codigo_perfil_encendido'])));
        $cloudData = $vmDao->getVmData($vm['codigo_vm']);
        $vmCloudSummary = array('id' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['id'],
            'name' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['name'],
            'displayname' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['displayname'],
            'hostid' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['hostid'],
            'hostname' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['hostname'],
            'instancename' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['instancename'],
            'state' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['state'],
            'cpuspeed' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['cpuspeed'],
            'cpunumber' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['cpunumber'],
            'serviceofferingname' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['serviceofferingname'],
            'memory' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['memory'],
            'ipaddress' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['nic'][0]['ipaddress'],
            'networkname' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['nic'][0]['networkname'],
            'netmask' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['nic'][0]['netmask'],
            'templatename' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['templatedisplaytext'],
            'gateway' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['nic'][0]['gateway']);
//$cloudToString = print_r($vmCloudSummary, true);
//$debugLog->debug("cloudToString : " . $cloudToString);
        if ($vm) {
            $this->view->codigo_vm = $vm['codigo_vm'];
            $this->view->displayname = $vmCloudSummary['displayname'];
            $this->view->codigo_vm = $vmCloudSummary['id'];
            $this->view->cpuSpeed = $vmCloudSummary['cpuspeed'];
            $this->view->cpuNumber = $vmCloudSummary['cpunumber'];
            $this->view->memory = $vmCloudSummary['memory'];
            $this->view->networkName = $vmCloudSummary['networkname'];
            $this->view->ip = $vmCloudSummary['ipaddress'];
            $this->view->gateway = $vmCloudSummary['gateway'];
            $this->view->netmask = $vmCloudSummary['netmask'];
            $this->view->instanceName = $vmCloudSummary['instancename'];
            $this->view->hostName = $vmCloudSummary['hostname'];
            $this->view->state = strtolower($vmCloudSummary['state']);
            $this->view->templatename = strtolower($vmCloudSummary['templatename']);

// perfil encendido
            $this->view->dias = $perfilEncendido['dias_encendido'];
            $this->view->horaInicioDia = $perfilEncendido['hora_inicio_dia'];
            $this->view->horaFinDia = $perfilEncendido['hora_fin_dia'];
            $this->view->horasDiarias = $perfilEncendido['horas_utilizacion_diario'];
            $this->view->horasCurso = $perfilEncendido['horas_utilizacion_curso'];
//$this->view->fueraHorario = ($perfilEncendido['permite_fuera_horario'] == 'N') ? 'No' : 'S&iacute;';
//            laboratorio
            $this->view->nombreLaboratorio = $laboratorio['nombre'];
            $this->view->codigoLaboratorio = $laboratorio['codigo_laboratorio'];

//            invocamos al script para datos del hypervisor para VNC
//$this->debugLog->debug(VirtualLabs_Script_Bash::BASH_INTERPRETER . " " . SCRIPT_PATH . VirtualLabs_Script_Bash::VM_VNC_DISPLAY_NUMBER . " {$vmCloudSummary['hostname']} {$vmCloudSummary['instancename']} ");
            ob_start();
            $this->view->port = system(VirtualLabs_Script_Bash::BASH_INTERPRETER . " " . SCRIPT_PATH . VirtualLabs_Script_Bash::VM_VNC_DISPLAY_NUMBER . " {$vmCloudSummary['hostname']} {$vmCloudSummary['instancename']} ");
            ob_clean();
        } else {
            echo '';
        }
    }

    public function indexAction() {
        
    }

    private function getVmData($vmId) {
        $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
        $vmCloud = new VirtualLabs_Rest_VirtualLabs_VirtualMachine();
        try {
            $vm = $vmCloud->listVM($vmId);
            $debugLog->debug(print_r(Zend_Json_Decoder::decode($vm), true));
            $cloudData = Zend_Json_Decoder::decode($vm);
            return array('name' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['name'],
                'displayname' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['displayname'],
                'state' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['state'],
                'hostid' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['hostid'],
                'cpuspeed' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['cpuspeed'],
                'cpunumber' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['cpunumber'],
                'serviceofferingname' => $cloudData['listvirtualmachinesresponse'][0]['virtualmachine']['serviceofferingname'],
                'memory' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['memory'],
                'ipaddress' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['nic'][0]['ipaddress'],
                'networkname' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['nic'][0]['networkname'],
                'gateway' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['nic'][0]['gateway'],
                'so' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['templatedisplaytext']);
        } catch (Exception $e) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->err($e->getMessage());
            $debugLog->err($e->getTraceAsString());
        }
    }

    public function myvmsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $lab = new VirtualLabs_Academico_Machine();
        $identity = Zend_auth::getInstance()->getIdentity();

        $machines = $lab->getVmsByUsername($identity['username']);

        $response = array();
        foreach ($machines as $vm) {
            if ($vm['codigo_vm'] != null) {
                $vmCloudSummary = $this->getVmData($vm['codigo_vm']);
                $date = new DateTime($vm['fecha_creacion']);
                $d = $date->format('d/m/Y');
                ;
                $response[] = array(
                    "<div class='col-sm-2 col-md-2'>" .
                    "<img src='/images/vm.jpg' style='width: 72px; height: 72px;'>" .
                    "</div>" .
                    "<div class='col-sm-4 col-md-4'>" .
                    "<a href='/academico/maquinaalumno/vm/codigo_maquina_virtual/{$vm['codigo_maquina_virtual']}'>" . $vmCloudSummary['displayname'] . "</a><br/>" .
                    "<span>Lab </span><a href='/academico/laboratorioalumno/lab/codigo_laboratorio/{$vm['codigo_laboratorio']}'>{$this->getLabName($vm['codigo_laboratorio'])}</a><br/>" .
                    "<span>Estado: </span><span class='{$this->vmstateclass($vmCloudSummary['state'])}'><strong>{$vmCloudSummary['state']}</strong></span>" .
                    "</div>" .
                    "<div class='col-sm-6 col-md-6'>" .
                    "<span><strong>Fecha de Creacion= </strong></span>" . $d . "<br />" .
                    "<span><strong>CPU= </strong></span>" . $vmCloudSummary['cpunumber'] . " de " . $vmCloudSummary['cpuspeed'] . " MHz. " .
                    "<span><strong>Memoria= </strong></span>" . $vmCloudSummary['memory'] . " MB<br />" .
                    "<span><strong>Sistema Operativo= </strong></span>" . $vmCloudSummary['so'] .
                    "</div>"
                );
            } else {
                $date = new DateTime($vm['fecha_creacion']);
                $d = $date->format('d/m/Y');
                ;
                $response[] = array(
                    "<div class='col-sm-2 col-md-2'>" .
                    "<img src='/images/vm.jpg' style='width: 72px; height: 72px;'>" .
                    "</div>" .
                    "<div class='col-sm-4 col-md-4'>" .
                    "<span class='{$this->vmstateclass($vmCloudSummary['state'])}'><strong>PENDIENTE DE CREACI&Oacute;N</strong></span><br/>"
                );
            }
        }
        $aaData['aaData'] = $response;
        echo Zend_Json_Encoder::encode($aaData);
    }

    private function permiteEncender($codigoVM) {
        try {
            $dayWeek = array(
                'Mon' => 'Lu',
                'Tue' => 'Ma',
                'Wed' => 'Mi',
                'Thu' => 'Ju',
                'Fri' => 'Vi',
                'Sat' => 'Sa',
                'Sun' => 'Do'
            );
            $retval = false;
            $vmDao = new VirtualLabs_Admin_Machine();
            $peDao = new VirtualLabs_Admin_PerfilEncendido();
            $labDao = new VirtualLabs_Admin_Laboratorio();

            //$labDao = new VirtualLabs_Admin_Laboratorio();
            //recuperamos el codigo de la maquina virtual y el codigo del perfil de encendido para efectivamente obtener luego el perfil de encendido
            //$vm = $vmDao->getVirtualMachine(array('codigo_maquina_virtual', 'codigo_perfil_encendido', 'codigo_laboratorio'), array('codigo_vm' => array('criteria' => '=', 'value' => $codigoVM)));
            $vm = $vmDao->getVirtualMachine(array('codigo_maquina_virtual', 'codigo_laboratorio'), array('codigo_vm' => array('criteria' => '=', 'value' => $codigoVM)));

            //recuperamos el codigo de perfil de encendido del laboratorio a partir del codigo de laboratorio
            $lab = $labDao->getLaboratorio('codigo_perfil_encendido', array('codigo_laboratorio' => array('criteria' => '=', 'value' => $vm['codigo_laboratorio'])));

            //una vez obtenido el codigo de perfil encendido obtener datos de la tabla perfil_encendido
            //$pe = $peDao->getPerfilEncendido(array('codigo_perfil_encendido', 'dias_encendido', 'hora_inicio_dia', 'hora_fin_dia', 'horas_utilizacion_diario', 'horas_utilizacion_curso', 'permite_fuera_horario'), array('codigo_perfil_encendido' => array('criteria' => '=', 'value' => $vm['codigo_perfil_encendido'])));
            $pe = $peDao->getPerfilEncendido(array('codigo_perfil_encendido', 'dias_encendido', 'hora_inicio_dia', 'hora_fin_dia', 'horas_utilizacion_diario', 'horas_utilizacion_curso', 'permite_fuera_horario'), array('codigo_perfil_encendido' => array('criteria' => '=', 'value' => $lab['codigo_perfil_encendido'])));

            $today = $dayWeek[date('D')];

            $pos = strpos($pe['dias_encendido'], $today); //esta funcion retorna false el dia no esta en el array
            if ($pos === FALSE) {
                $retval = false;
            } else {

                $hora_inicio = strtotime(date("Y-m-d") . " " . $pe['hora_inicio_dia']);
                $hora_fin = strtotime(date("Y-m-d") . " " . $pe['hora_fin_dia']);
                $hora_actual = strtotime(date("Y-m-d H:i:s"));
                if (($hora_fin >= $hora_actual) && ($hora_actual >= $hora_inicio)) {
                    $retval = true;
                } else {
                    $retval = false;
                }
            }
            // En caso de que $retval sea false, verificar la configuracion global..
            if ($retval === FALSE) {
                $capacityDao = new VirtualLabs_Admin_Capacity();
                $capacity = $capacityDao->getConfigCapacityNow();
                $cpu_percent = $capacity['cantidad_cpu'];
                $mem_percent = $capacity['cantidad_ram'];
                if ($cpu_percent > 0 AND $mem_percent > 0) {
                    //traer la capacidad del sistema (porcentaje utilizado y total de recursos)
                    $systemCapacity = $this->getSystemCapacity();
                    $vmCapacity = $this->getVmData($codigoVM);
                    $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
                    $debugLog->debug("System Capacity: " . print_r($systemCapacity, TRUE));
                    $debugLog->debug("VM Capacity: " . print_r($vmCapacity, TRUE));

                    $curcpuper = $systemCapacity['cpu'];            //porcentaje de cpu utilizado actualmente
                    $curmemper = $systemCapacity['memory'];         //porcentaje de memoria utilizada actualmente
                    $totcpu = $systemCapacity['cputotal'];          //total de cpu del sistema (en MHZ)
                    $totmemory = $systemCapacity['memtotal'];       //total de memoria del sistema (en MB)
                    $vmcpu = $vmCapacity['cpuspeed'];               //cpu utilizada por la vm (en CPU)
                    $vmmem = $vmCapacity['memory'];                 //memoria utilizada por la vm (en MB)

                    $vmcpuper = $vmcpu / $totcpu * 100;             //porcentaje de cpu utilizada por la vm
                    $vmmemper = $vmmem / $totmemory * 100;          //porcentaje de memoria utilizada por la vm

                    $totcpuper = $curcpuper + $vmcpuper;
                    $totmemper = $curmemper + $vmmemper;
                    $debugLog->debug("CPU Percent total: {$totcpuper} MEMORY Percenttotal: {$totmemper} ");

                    if ($cpu_percent >= $totcpuper AND $mem_percent >= $totmemper) {
                        $retval = TRUE;
                    }
                }
            }
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getMessage());
            $debugLog->debug($exc->getTraceAsString());
            $retval = false;
        }
        return $retval;
    }

    /*
     * retorna la clase css asignada para el texto del estado de la maquina virtual
     */

    private function vmstateclass($state) {
        $result = 'text-muted';
        if ($state == 'Stopped') {
            $result = 'text-danger';
        } elseif ($state == 'Running') {
            $result = 'text-success';
        }
        return $result;
    }

    /*
     * Segun el codigo de Laboratorio, obtiene el nombre del mismo
     */

    private function getLabName($codigo_lab) {
        $lab = new VirtualLabs_Admin_Laboratorio();
        $datosLaboratorio = $lab->getLaboratorio('*', array('codigo_laboratorio' => array('criteria' => '=', 'value' => $codigo_lab)));
        return $datosLaboratorio['nombre'];
    }

    public function getvmstatusAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        try {
            $codigo_vm = $this->getRequest()->getParam('codigo_vm');
            $vmDao = new VirtualLabs_Admin_Machine();
            $cloudData = $vmDao->getVmData($codigo_vm);
            $estado = $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['state'];
            echo Zend_Json_Encoder::encode(array('response' => $estado));
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getMessage());
            $debugLog->debug($exc->getTraceAsString());
            echo Zend_Json_Encoder::encode(array('response' => 'error', 'message' => $exc->getMessage()));
        }
    }

    public function checkvmstatusAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $id = $this->getRequest()->getParam('jobid');

        if (!$id)
            return;
        $restUtil = new VirtualLabs_Rest_Util();
        try {
            $vmCloudData = $restUtil->jobStatus($id);
            //$vmCloudDataToString = print_r($vmCloudData, true);            
            if (VirtualLabs_Rest_Util::STOP_VM_CMD == $vmCloudData['queryasyncjobresultresponse']['cmd']) {
                if (strtolower($vmCloudData['queryasyncjobresultresponse']['jobresult']['virtualmachine']['state']) == VirtualLabs_Admin_Machine::ESTADO_POWEROFF) {
                    echo Zend_Json_Encoder::encode(array('response' => 'OK'));
                } else {
                    echo Zend_Json_Encoder::encode(array('response' => 'ERROR'));
                }
            } else if (VirtualLabs_Rest_Util::START_VM_CMD == $vmCloudData['queryasyncjobresultresponse']['cmd']) {
                if (strtolower($vmCloudData['queryasyncjobresultresponse']['jobresult']['virtualmachine']['state']) == VirtualLabs_Admin_Machine::ESTADO_ENCENDIDO) {
                    echo Zend_Json_Encoder::encode(array('response' => 'OK'));
                } else {
                    echo Zend_Json_Encoder::encode(array('response' => 'ERROR'));
                }
            }
        } catch (Exception $e) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($e->getMessage());
            $debugLog->debug($e->getTraceAsString());
        }
    }

    public function getconnparamAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        try {
            $codigo_vm = $this->getRequest()->getParam('codigo_vm');
            $vmDao = new VirtualLabs_Admin_Machine();
            $vm = $vmDao->getVirtualMachine(array("codigo_vm", "codigo_maquina_virtual"), array('codigo_vm' => array('criteria' => '=', 'value' => $codigo_vm)));
            $identity = Zend_auth::getInstance()->getIdentity();
            echo Zend_Json_Encoder::encode(array('response' => 'ok', 'codigo_vm' => $vm['codigo_maquina_virtual'], 'username' => $identity['username']));
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getMessage());
            $debugLog->debug($exc->getTraceAsString());
            echo Zend_Json_Encoder::encode(array('response' => 'error', 'message' => $exc->getMessage()));
        }
    }

    /*
     *  Obtiene la capacidad del sistema y la 
     */

    private function getSystemCapacity() {
        $util = new VirtualLabs_Rest_Util();
        $response = array();
        try {
            $capacity = $util->listCapacity();
            if (isset($capacity['listcapacityresponse']['count'])) {
                if ($capacity['listcapacityresponse']['count'] > 0) {
                    foreach ($capacity['listcapacityresponse']['capacity'] as $c) {
                        switch ($c['type']) {
                            case self::CAPACITY_TYPE_CPU:
                                $response['cpu'] = $c['percentused'];
                                $response['cputotal'] = $c['capacitytotal'];
                                break;
                            case self::CAPACITY_TYPE_MEMORY:
                                $response['memory'] = $c['percentused'];
                                $response['memtotal'] = (int) number_format(($c['capacitytotal'] / 1024 / 1024), 0, ',', '');
                                break;
                            case self::CAPACITY_TYPE_STORAGE:
                                $response['storage'] = $c['percentused'];
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            return $response;
        } catch (Exception $e) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($e->getMessage());
            $debugLog->debug($e->getTraceAsString());
            throw $e;
        }
    }

    public function managevmAction() {
        $this->_helper->layout->disableLayout();

        try {
            $codigo_maquina_virtual = $this->getRequest()->getParam('codigo');
            $vmDao = new VirtualLabs_Admin_Machine();
            $vmDao2 = new VirtualLabs_Academico_Machine();
            $vm = $vmDao->getVirtualMachine(array("codigo_vm", "codigo_maquina_virtual"), array('codigo_maquina_virtual' => array('criteria' => '=', 'value' => $codigo_maquina_virtual)));
            $identity = Zend_auth::getInstance()->getIdentity();

            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug("vm : " . print_r($vm, TRUE));

            if ($vmDao2->isUserVm($identity['username'], $codigo_maquina_virtual)) { //evaluamos si la vm pertenece al usuario
                $cloudData = $vmDao->getVmData($vm['codigo_vm']);
                $estado = $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['state'];
                if ($estado == 'Running') {
                    $hostname = $estado = $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['hostname'];
                    $instance = $estado = $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['instancename'];
                    ob_start();
                    $port = system(VirtualLabs_Script_Bash::BASH_INTERPRETER . " " . SCRIPT_PATH . VirtualLabs_Script_Bash::VM_VNC_DISPLAY_NUMBER . " {$hostname} {$instance} ");
                    ob_clean();
                    $this->view->port = $port;
                    $this->view->hostName = $hostname;
                } else {
                    $this->_redirect('/academico/maquinaalumno/errorvm/error/2');
                }
            } else {
                $this->_redirect('/academico/maquinaalumno/errorvm/error/1');
            }
        } catch (Exception $exc) {
            $debugLog = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
            $debugLog->debug($exc->getMessage());
            $debugLog->debug($exc->getTraceAsString());
            echo Zend_Json_Encoder::encode(array('response' => 'error', 'message' => $exc->getMessage()));
        }
    }

    public function errorvmAction() {
        $this->_helper->layout->disableLayout();
        $codigo_error = $this->getRequest()->getParam('error');
        if ($codigo_error == 1) {
            $this->view->error = "Deja de Hacerte el vivo, esta VM no te pertenece";
        } elseif ($codigo_error == 2) {
            $this->view->error = "La maquina no esta disponible para ser accedida";
        } else {
            $this->view->error = "Error inesperado";
        }
    }

    public function refreshvmAction() {
        $this->_helper->layout->disableLayout();
        $vmAcademicoDao = new VirtualLabs_Academico_Machine();
        $vms = $vmAcademicoDao->getVMWithAjobId();
        $rest = new VirtualLabs_Rest_Util();
        foreach ($vms as $vm) {
            $response = $rest->jobStatus($vm['async_job_id']);
            if (isset($response['queryasyncjobresultresponse']['jobresult']['errorcode'])) {
                $data = array('estado' => 'E', 'async_job_id' => '');
                $vmAcademicoDao->save(VirtualLabs_Academico_Machine::TABLE_NAME, $data, array('key' => 'codigo_maquina_virtual', 'value' => $vm['codigo_maquina_virtual']));
            } else if (isset($response['queryasyncjobresultresponse']['jobresult']['virtualmachine']['id'])) {
                $data = array('codigo_vm' => $response['queryasyncjobresultresponse']['jobresult']['virtualmachine']['id'], 'estado' => 'A', 'async_job_id' => '');
                $vmAcademicoDao->save(VirtualLabs_Academico_Machine::TABLE_NAME, $data, array('key' => 'codigo_maquina_virtual', 'value' => $vm['codigo_maquina_virtual']));
            }
        }
    }

}

